/**
 * SpringMVC restful 风格
 * 用户控制器，控制关于代理商审核的一些业务逻辑操作
 * @author WangXinLei
 * @date 2014-12-09
 */
package com.chnbst.bstyun.controller.admin;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.task.TaskExecutor;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.chnbst.bstyun.core.common.Pager;
import com.chnbst.bstyun.core.common.SignUtil;
import com.chnbst.bstyun.core.common.email.EmailUtil;
import com.chnbst.bstyun.model.pojo.Email;
import com.chnbst.bstyun.model.pojo.Supplier;
import com.chnbst.bstyun.model.pojo.User;
import com.chnbst.bstyun.model.vo.SupplierVo;
import com.chnbst.bstyun.service.EmailService;
import com.chnbst.bstyun.service.SupplierService;
import com.chnbst.bstyun.service.UserService;
//import com.chnbst.mail.EmailUtil;


/**
 * 控制器注解 请求映射注解
 * controller 代表类是控制器
 * restcontroller 代表类是控制器， 所有的方法 都是ajax方法
 * @author WangXinLei
 *
 */

@Controller
@RequestMapping("/sysAdmin")
public class SupplierAdminController {
	//每页显示的用户数
	private int pageSize = 10;
	//用户列表页码
	private int currPage = 1;
	
	private static final String ROLE_COMPANY = "ROLE_COMPANY";//公司用户
	private static final String ROLE_PERSON = "ROLE_PERSON";//个人用户
	private static final String ROLE_AGENT = "ROLE_AGENT";//代理商
	/**
	 * 注入 业务逻辑层
	 */
	@Autowired
	private UserService userService;
	@Autowired
	private SupplierService supplierService;
	@Resource 
	private TaskExecutor taskExecutor;//注入Spring封装的异步执行器
	@Autowired
	private EmailService emailService;
	
	/**
	 * @return 代理商审核页面
	 * @throws Exception
	 */
	@RequestMapping(value="/supplier/supplierAudit",method=RequestMethod.GET)
	public ModelAndView supplierAudit()throws Exception{
		return new ModelAndView("admin/supplierManager/supplierManager");
	}
	
	/**
	 * Ajax 分页查询代理商审核list
	 * @return 代理商审核列表页面
	 * @throws Exception
	 */
	@RequestMapping(value="/supplier/supplierAudit/search",method=RequestMethod.POST)
	@ResponseBody
	public Map<String, Object> supplierAudit(String page,String last,HttpServletRequest request)throws Exception{
		Map<String, Object> map = new HashMap<String, Object>();
		
		String applyState = request.getParameter("applyState");
		String applyType = request.getParameter("applyType");
		
		if(SignUtil.isNotEmpty(page)) {
			currPage = Integer.valueOf(page);
		}
		
		if(SignUtil.isNotEmpty(last)) {
			pageSize = Integer.valueOf(last);
		}

		map.put("applyType", applyType);
		map.put("applyState", applyState);
		
		int totalRows = supplierService.selectSupplierCountByCondition(map);
		int pageCount = Pager.getPageCount(totalRows, pageSize);
		if(pageCount < currPage) {
			currPage = pageCount;
		}
		int start = Pager.getStart(currPage, pageSize);
		
		map.put("start", start);
		map.put("pageSize", pageSize);
		map.put("sortField", "s.supplier_id");
		map.put("sortOrder", "desc");
		
		List<SupplierVo> userList = supplierService.selectSupplierVoByCondition(map);
		
		Map<String, Object> resultMap = new HashMap<String, Object>();
		resultMap.put("page", currPage);
		resultMap.put("pageCount", pageCount);
		resultMap.put("totalRows", totalRows);
		resultMap.put("userList", userList);
		
		return resultMap;
	}
	  
	/**
	 * 根据ID查询代理商的详细信息
	 * @return 代理商详情页面
	 * @throws Exception
	 */
	@RequestMapping(value="/supplier/supplierDetail/{supplierId}",method=RequestMethod.GET)
	public ModelAndView supplierDetail(@PathVariable Integer supplierId)throws Exception{
		
		ModelAndView mav = new ModelAndView();
		
		//加载代理商的详细信息
		SupplierVo supplierInfo = supplierService.selectSupplierVoBySupplierId(supplierId);
		
		mav.addObject("supplierInfo", supplierInfo);
		mav.setViewName("admin/supplierManager/supplierDetail");
		
		return mav;
	}
	
	/**
	 * 根据ID和按钮id修改代理商审核的状态
	 * @return true 或者false
	 * @throws Exception
	 */
	@RequestMapping(value="/operate/supplier/updateSupplier",method=RequestMethod.POST)
	@ResponseBody
	public boolean updateSupplier(HttpServletRequest request,Integer supplierId,
			Integer applyState,Integer applyType,Double mealPrivilege,Double proPrivilege,String returnReason) throws Exception{
		
		Supplier supplier = supplierService.selectSupplierBySupplierId(supplierId);
		supplier.setApplyState(applyState);
		supplier.setMealPrivilege(mealPrivilege);
		supplier.setProPrivilege(proPrivilege);
		supplier.setApplyType(applyType);
		supplier.setReturnReason(returnReason);
		
		boolean b = supplierService.updateBySupplierId(supplier);
		User user = userService.selectUserInfoByUserId(supplier.getUserId());
		
		if(b){
			String applyTypeStr = "";
			if(applyType == 1) {
				applyTypeStr = "代理商加盟";
			}else if(applyType == 2) {
				applyTypeStr = "市总代加盟";
			}else if(applyType == 3) {
				applyTypeStr = "省总代加盟";
			}else if(applyType == 4) {
				applyTypeStr = "软件开发商加盟";
			}else if(applyType == 5) {
				applyTypeStr = "OEM商合作";
			}else if(applyType == 6) {
				applyTypeStr = "销售人员";
			}
			
			String account = "";
			if(SignUtil.isNotEmpty(user.getUserEmail())) {
				account = user.getUserEmail();
			}else {
				account = user.getUserTel();
			}
			
			if(applyState == 1) {
				supplier.setIsValid(1);
				supplierService.updateBySupplierId(supplier);
				user.setRoleId(ROLE_AGENT);
				userService.updateUser(user);
				String mealPrivilegeStr = ((int)(mealPrivilege*100)) + "%";
				String proPrivilegeStr = ((int)(proPrivilege*100)) + "%";
				String type = applyTypeStr;
				String userAccount = account;
				
				taskExecutor.execute(new Runnable(){
				    public void run(){
					    try {
					    	Email email = emailService.selectEmail(29);
					    	String content = email.getEmailContent();
					    	content = content.replace("arg0", userAccount).replace("arg1", type).replace("arg2", mealPrivilegeStr).replace("arg3", proPrivilegeStr);
					    	EmailUtil.sendMail(supplier.getUserEmail(), email.getEmailSubject(), content+email.getEmailSign());
//					    	EmailUtil.sendMailApplySuccess(supplier.getUserEmail(),new String[]{userAccount,type,mealPrivilegeStr,proPrivilegeStr});
					    } catch (Exception e) {
					        e.printStackTrace();
					    }
				    }
			    });
				
			}else if(applyState == 2) {
				user.setSupplierId(null);
				userService.updateUser(user);
				String type = applyTypeStr;
				String userAccount = account;
				
				taskExecutor.execute(new Runnable(){
				    public void run(){
					    try {
					    	Email email = emailService.selectEmail(30);
					    	String content = email.getEmailContent();
					    	content = content.replace("arg0", userAccount).replace("arg1", type).replace("arg2", returnReason);
					    	EmailUtil.sendMail(supplier.getUserEmail(), email.getEmailSubject(), content+email.getEmailSign());
//					    	EmailUtil.sendMailApplyReturn(supplier.getUserEmail(),new String[]{userAccount,type,returnReason});
					    } catch (Exception e) {
					        e.printStackTrace();
					    }
				    }
			    });
			}
		}	
		return b;
	}
	
	/**
	 * 根据ID和按钮id 重新审核代理商状态
	 * @return true 或者false
	 * @throws Exception
	 */
	@RequestMapping(value="/operate/supplier/resetSupplier",method=RequestMethod.POST)
	@ResponseBody
	public boolean resetSupplier(HttpServletRequest request,Integer supplierId,
			Integer applyType,Double mealPrivilege,Double proPrivilege) throws Exception{
		
		Supplier supplier = supplierService.selectSupplierBySupplierId(supplierId);
		
		supplier.setMealPrivilege(mealPrivilege);
		supplier.setProPrivilege(proPrivilege);
		supplier.setApplyType(applyType);
		
		boolean b = supplierService.updateBySupplierId(supplier);
		User user = userService.selectUserInfoByUserId(supplier.getUserId());
		
		if(b){
			String applyTypeStr = "";
			if(applyType == 1) {
				applyTypeStr = "代理商加盟";
			}else if(applyType == 2) {
				applyTypeStr = "市总代加盟";
			}else if(applyType == 3) {
				applyTypeStr = "省总代加盟";
			}else if(applyType == 4) {
				applyTypeStr = "软件开发商加盟";
			}else if(applyType == 5) {
				applyTypeStr = "OEM商合作";
			}else if(applyType == 6) {
				applyTypeStr = "销售人员";
			}
			
			String account = "";
			if(SignUtil.isNotEmpty(user.getUserEmail())) {
				account = user.getUserEmail();
			}else {
				account = user.getUserTel();
			}

			String mealPrivilegeStr = ((int)(mealPrivilege*100)) + "%";
			String proPrivilegeStr = ((int)(proPrivilege*100)) + "%";
			String type = applyTypeStr;
			String userAccount = account;
			
			taskExecutor.execute(new Runnable(){
			    public void run(){
				    try {
				    	Email email = emailService.selectEmail(31);
				    	String content = email.getEmailContent();
				    	content = content.replace("arg0", userAccount).replace("arg1", type).replace("arg2", mealPrivilegeStr).replace("arg3", proPrivilegeStr);
				    	EmailUtil.sendMail(supplier.getUserEmail(), email.getEmailSubject(), content+email.getEmailSign());
				    	
//				    	EmailUtil.sendMailUpdateApplySuccess(supplier.getUserEmail(),new String[]{userAccount,type,mealPrivilegeStr,proPrivilegeStr});
				    } catch (Exception e) {
				        e.printStackTrace();
				    }
			    }
		    });
		}
		return b;
	}
	
	/**
	 * 根据ID和userValid修改有效状态
	 * @return true 或者false
	 * @throws Exception
	 */
	@RequestMapping(value="/operate/supplier/SupplierUpdateIsValid",method=RequestMethod.POST)
	@ResponseBody
	public Map<String, Object> SupplierUpdateIsValid(HttpServletRequest request,Integer supplierId,boolean flag) throws Exception{
		Supplier supplier = supplierService.selectSupplierBySupplierId(supplierId);
		User user = userService.selectUserInfoByUserId(supplier.getUserId());
		boolean isSuccess = false;
		Map<String, Object> map = new HashMap<String, Object>();
		if(flag) {
			//启用用户
			if("1".equals(supplier.getIsValid())) {
				map.put("message", "代理商已经是启动状态，无需启用！！");
			}else {
				supplier.setIsValid(1);

				boolean b =  supplierService.updateBySupplierId(supplier);
				if(b){
					user.setRoleId(ROLE_AGENT);
					isSuccess = userService.updateUser(user);
				}	
			}
		}else {
			//停用用户
			if("0".equals(supplier.getIsValid())) {
				map.put("message", "代理商已经是停用状态，无需停用！！");
			}else {
				supplier.setIsValid(0);
				//isSuccess =  supplierService.updateBySupplierId(supplier);
				boolean b =  supplierService.updateBySupplierId(supplier);
				if(b){
					user.setRoleId(ROLE_PERSON);
					isSuccess = userService.updateUser(user);
				}
				
			}
		}
		map.put("isSuccess", isSuccess);
		return map;
	}
}
